﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE80;
using TSVNAddin.SVN;
using System.IO;

namespace TSVNAddin.Core
{
	public class WorkingContext
	{
		private readonly SolutionAdapter _SolutionAdapter;
		private readonly SVNClientAdapter _SVNClientAdapter;

		private WorkingCopy _LastWorkingCopy;

		public WorkingContext(SolutionAdapter solutionAdapter, SVNClientAdapter svnClientAdapter)
		{
			_SolutionAdapter = solutionAdapter;
			_SVNClientAdapter = svnClientAdapter;
			ResetWorkingCopy();
		}

		public virtual string GetWorkingRoot()
		{
			return GetWorkingCopy().WorkingRoot;
		}

		public virtual bool CanExecutePathCommands()
		{
			if (!_SolutionAdapter.IsOpen())
				return false;

			if (!GetWorkingCopy().IsEnable())
				return false;

			return true;
		}

		public virtual bool CanExecuteCommandsOnPath(string path)
		{
			if (!CanExecutePathCommands())
				return false;

			return GetWorkingCopy().Contains(path);
		}

		public virtual bool CanExecuteCheckout()
		{
			if (!_SolutionAdapter.IsOpen())
				return false;

			if (GetWorkingCopy().IsEnable())
				return false;

			return true;
		}

		private WorkingCopy GetWorkingCopy()
		{
			string solutionFileName = _SolutionAdapter.GetFileName();

			if (_LastWorkingCopy.IsChanged(solutionFileName))
				return _LastWorkingCopy;

			string workingRoot = new WorkingRootFinder(_SVNClientAdapter).FindRoot(solutionFileName);

			if (workingRoot != string.Empty)
			{
				_LastWorkingCopy = new WorkingCopy(workingRoot, solutionFileName, true);
			}
			else
			{
				string newWorkingRoot = Path.GetDirectoryName(solutionFileName) + @"\";
				_LastWorkingCopy = new WorkingCopy(newWorkingRoot, solutionFileName, false);
			}

			return _LastWorkingCopy;
		}

		public virtual void ResetWorkingCopy()
		{
			_LastWorkingCopy = new WorkingCopy(string.Empty, string.Empty, false);
		}
	}
}
